import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'

// 路由懒加载  （异步组件）
// 当页面加载到这个组件的时候才会加载
const appTabbar = () => import('@/components/app-tabbar.vue')
const Home = () => import('../views/home')
const Question = () => import('../views/question/question.vue')
const Video = () => import('../views/video/video.vue')
const Mine = () => import('../views/mine/mine.vue')
const Login = () => import('../views/login/login.vue')
const Article = () => import('../views/article')
const Profile = () => import('../views/mine/components/profile.vue')
const Chat = () => import('../views/mine/components/chat.vue')

Vue.use(VueRouter)

/* 在创建router实例对象之前，手动覆盖原型链的push来吞掉报错catch */
// 先存储默认底层的push
const originPush = VueRouter.prototype.push
// 覆盖原型链的push
VueRouter.prototype.push = function (location, resolve, reject) {
  // this:路由实例对象

  // 判断用户有没有传后面两个可选参数
  if (resolve || reject) {
    return originPush.call(this, location, resolve, reject)
  } else { // 用户只传了第一个参数
    /*
      默认底层： catch()方法代码  throw err : 抛出异常
      吞掉报错原理： 重写catch()方法,把默认底层的 throw err给去掉，就不会抛出异常
      */
    return originPush.call(this, location).catch(() => {
      console.log()
    })
  }
}

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    components: {
      default: Home,
      tabbar: appTabbar
    }
  },
  {
    path: '/question',
    name: 'Question',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    // component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
    components: {
      default: Question,
      tabbar: appTabbar
    }
  },
  {
    path: '/video',
    components: {
      default: Video,
      tabbar: appTabbar
    }
  },
  {
    path: '/mine',
    components: {
      default: Mine,
      tabbar: appTabbar
    }
  },
  {
    path: '/mine/profile',
    component: Profile
  },
  {
    path: '/mine/chat',
    component: Chat
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/article',
    component: Article
  },
  {
    path: '*',
    redirect: '/home'
  }
]

const router = new VueRouter({
  routes
})

const blackList = ['/mine', '/cart']

// 路由前置守卫函数
router.beforeEach((to, from, next) => {
  // 清除之前的所有请求
  store.commit('user/clearBeforeHttp')
  const token = store.state.user.token
  // console.log(token)
  if (!token && blackList.includes(to.path)) {
    return next('/login?returnUrl=' + to.fullPath)
  }

  next()
})

export default router
